<template>
  <!-- 随机分配见证人 -->
  <!-- 定向分配见证人 -->
  <el-dialog :title="dialogTitle" :visible.sync="visible" width="600px" @close="closeFn">
    <div class="clear ui-mb10">
      <span class="float-right">
        <el-input v-model.trim="keyWord" placeholder="人员编号/姓名" class="ui-w320" @keydown="submitSearchFn">
          <el-button slot="append" type="primary" icon="el-icon-search" @click="submitSearchFn" />
        </el-input>
      </span>
    </div>
    <el-table
      :key="'table' + type"
      :data="tableData"
      :max-height="300"
      border
      stripe
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" label="选择" width="55">
        <template slot-scope="scope">
          <el-radio v-model="scope.row" label=""></el-radio>
        </template>
      </el-table-column> -->
      <el-table-column v-if="type == 'random'" label="选择" align="center" type="selection" width="55" />
      <el-table-column v-else label="选择" align="center" width="55">
        <template slot-scope="scope">
          <el-radio :key="scope.$index" v-model="userSelected" :label="scope.row.userId">&nbsp;</el-radio>
        </template>
      </el-table-column>
      <!-- ndustry 行业
industryType 行业类型
tenderMode 交易方式
枚举值: PUBLIC_BIDDING,INVITE_BIDDING
userCode 用户编码
userId 用户id
userIdCard 用户身份证号
userName 用户名称
userStatusEnum 用户状态
枚举值: ENABLE,DEACTIVATE
userTel 用户电话
witnessLinkPermission 用户权限码
witnessLinkPermissionAssist 用户权限辅助值
message -->
      <el-table-column type="index" align="center" label="序号" width="55" />
      <el-table-column label="见证人" min-width="105">
        <template slot-scope="scope">{{ scope.row.userName }}({{ scope.row.userCode }})</template>
      </el-table-column>
      <!-- <el-table-column prop="index" label="本月见证任务总量" width="55"> -->
      <!-- </el-table-column> -->
      <el-table-column prop="unWitnessTaskCount" align="center" label="待见证数量" min-width="55" />
      <el-table-column prop="ingWitnessTaskCount" align="center" label="见证中数量" min-width="55" />
      <el-table-column prop="finishWitnessTaskCount" align="center" label="已完成数量" min-width="55" />
    </el-table>
    <div class="layout-footer ui-pt10">
      <!-- {{ pageObj.total + " " + pageObj.pageSize }} -->
      <pagination
        v-if="pageObj.total >= 10"
        :total="pageObj.total"
        :page.sync="pageObj.currentPage"
        :limit.sync="pageObj.pageSize"
        :page-sizes="pageObj.pageSizes"
        @pagination="subtaskPermissionUserFn"
      />
    </div>
    <!-- 移交见证人 -->
    <el-form
      v-if="reasonFlag"
      ref="updateForm"
      class="ui-mt10"
      :model="updateForm"
      :rules="cancelRules"
      label-width="80px"
      :inline="false"
      size="normal"
      on-submit="return false;"
    >
      <el-form-item label="移交给" required prop="reason">
        <el-input v-model="updateForm.code" type="textarea" style="width: 100%" maxlength="200" show-word-limit />
      </el-form-item>
      <el-form-item label="更改原因" required prop="reason">
        <el-input v-model="updateForm.code" type="textarea" style="width: 100%" maxlength="200" show-word-limit />
      </el-form-item>
    </el-form>
    <span slot="footer">
      <el-button
        v-if="type == 'random'"
        type="primary"
        :disabled="!multipleSelection.length"
        :loading="loading"
        @click="submitFn"
      >
        随机分配
      </el-button>
      <el-button v-else type="primary" :disabled="!userSelected.length" :loading="loading" @click="submitFn">
        确定
      </el-button>
      <el-button @click="cancelFn()">取消</el-button>
    </span>
  </el-dialog>
</template>
<script>
  import { subtaskPermissionUser, subtaskAllocateUser, subtaskAllocateUserRandom } from "../../api/api.js";
  export default {
    name: "AssignDialog",
    components: {},
    props: {
      type: {
        type: String,
        default: ""
      },
      headerTitle: {
        type: String,
        default: ""
      },
      data: {
        type: Array,
        default() {
          return [];
        }
      },
      rowData: {
        type: Object,
        default() {
          return {};
        }
      },
      show: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        multipleSelection: [],
        cancelRules: {
          reason: [
            { required: true, message: "原因不能为空", trigger: "blur" },
            { required: true, message: "原因不能为空", trigger: "change" }
          ]
          // code: [
          //   {
          //     validator: validateCode,
          //     trigger: "blur",
          //   },
          //   { required: true, message: "验证码不能为空", trigger: "change" },
          // ],
        },
        updateForm: {
          reason: ""
        },
        dialogTitle: "",
        userSelected: "",
        taskList: [],
        reasonFlag: false,
        loading: false,
        visible: false,
        keyWord: "",
        tableData: [],
        tableDataOld: [],
        pageObj: {
          total: 0,
          currentPage: 1,
          pageSize: 10,
          pageSizes: [10, 20, 30]
        },
        pageSizes: [10, 20, 30]
      };
    },
    computed: {
      // visible() {
      //   return this.show;
      // },
    },
    watch: {
      // data() {
      //   this.taskList = this.data;
      // },
      show() {
        this.visible = this.show;
        this.userSelected = "";
        this.multipleSelection = [];
        this.reasonFlag = false;
        if (this.headerTitle) {
          this.dialogTitle = this.headerTitle;
        } else {
          this.dialogTitle = this.type === "random" ? "随机分配见证人" : "定向分配见证人";
        }
        if (this.show) {
          let witnessSubTaskId = [];
          console.log("this.rowData", this.rowData);
          if (this.headerTitle === "分配见证人" || this.headerTitle === "更改见证人") {
            witnessSubTaskId = [this.rowData.witnessSubTaskId];
          } else if (this.headerTitle === "移交见证人") {
            witnessSubTaskId = [this.rowData.witnessSubTaskId];
            this.reasonFlag = true;
          }else if(this.headerTitle === "更改项目见证人"){
            witnessSubTaskId = this.rowData.bidList.reduce((arr, item) => {
              if(item['OPERATE_UPDATE_WITNESS_USER'] === true) {
                arr.push(item.witnessSubTaskId);
              }
              return arr
            }, [])
          } else {
            console.log("this.data", this.data);
            this.data.forEach((item) => {
              witnessSubTaskId.push(item.data.witnessSubTaskId);
            });
          }
          this.witnessSubTaskId = witnessSubTaskId;
          console.log("witnessSubTaskId", witnessSubTaskId.join());
          this.subtaskPermissionUserFn();
        }
      }
    },
    methods: {
      cancelFn() {
        this.visible = false;
      },
      closeFn() {
        this.keyWord = "";
        this.userSelected = "";
        this.$emit("close");
      },
      submitFn() {
        this.loading = true;
        this.$nextTick(() => {
          if (this.type === "random") {
            this.subtaskAllocateUserRandomFn();
          } else {
            this.subtaskAllocateUserFn();
          }
        });
      },
      // 搜索
      submitSearchFn() {
        this.tableData = this.tableDataOld.filter(
          (item) => item.userCode.indexOf(this.keyWord) > -1 || item.userName.indexOf(this.keyWord) > -1
        );
      },
      // list
      async subtaskPermissionUserFn() {
        try {
          // this.pageObj.pageSize;
          // 分页影响下拉菜单数据
          const p = {
            pageSize: -1,
            witnessSubTaskIdList: this.witnessSubTaskId
          };
          const res = await subtaskPermissionUser(p);
          this.loading = false;
          if (res.success) {
            this.tableData = res.data.data;
            this.tableDataOld = res.data.data;
            // } else {
          }
        } catch (error) {
          console.error(error);
        }
      },
      // 提交
      async subtaskAllocateUserFn() {
        try {
          // witnessSubTaskAllocateType 分配方式
          // ASSIGN_ALLOCATE 定向分配、分配见证人
          // UPDATE_ALLOCATE 更改见证人
          // TRANSFER_ALLOCATE 移交见证人
          // reason 原因，更改、移交时需要填写原因
          const p = {
            userId: this.userSelected,
            witnessSubTaskIdList: this.witnessSubTaskId,
            witnessSubTaskAllocateType: "ASSIGN_ALLOCATE"
          };
          if (this.headerTitle === "更改见证人" || this.headerTitle === "更改项目见证人" ) {
            p.witnessSubTaskAllocateType = "UPDATE_ALLOCATE";
          } else if (this.headerTitle === "移交见证人") {
            p.witnessSubTaskAllocateType = "TRANSFER_ALLOCATE";
            p.reason = this.updateForm.reason;
          }
          const res = await subtaskAllocateUser(p);
          if (res.success) {
            this.$message({
              type: "success",
              message: res.message || "操作成功",
              single: true
            });
            const userObj = this.tableData.filter((item) => item.userId === this.userSelected);
            this.$emit("close", this.headerTitle === "更改项目见证人" ? 'refresh' : "save", userObj);
          } else {
            this.$message({
              type: "error",
              message: res.message || "获取数据失败，请稍后再试",
              single: true
            });
          }
        } catch (error) {
          this.$message({
            type: "error",
            message: "获取数据失败，请稍后再试",
            single: true
          });
        }
        this.loading = false;
      },
      // 提交-随机分配
      async subtaskAllocateUserRandomFn() {
        try {
          // witnessSubTaskAllocateType 分配方式
          // ASSIGN_ALLOCATE 定向分配、分配见证人
          // UPDATE_ALLOCATE 更改见证人
          // TRANSFER_ALLOCATE 移交见证人
          // reason 原因，更改、移交时需要填写原因
          // multipleSelection
          const allocateUserIds = this.multipleSelection.map((item) => item.userId);
          const p = {
            allocateUserIds,
            witnessSubTaskIdList: this.witnessSubTaskId
            // witnessSubTaskAllocateType: "ASSIGN_ALLOCATE",
          };
          // if (this.headerTitle == "更改见证人") {
          //   p.witnessSubTaskAllocateType = "UPDATE_ALLOCATE";
          // } else if (this.headerTitle == "移交见证人") {
          //   p.witnessSubTaskAllocateType = "TRANSFER_ALLOCATE";
          //   p.reason = this.updateForm.reason;
          // }
          const res = await subtaskAllocateUserRandom(p);
          if (res.success) {
            this.$message({
              type: "success",
              message: res.message || "操作成功",
              single: true
            });
            this.$emit("close", "save");
          } else {
            this.$message({
              type: "error",
              message: res.message || "获取数据失败，请稍后再试",
              single: true
            });
          }
        } catch (error) {
          this.$message({
            type: "error",
            message: "获取数据失败，请稍后再试",
            single: true
          });
        }
        this.loading = false;
      },
      handleSelectionChange(val) {
        console.log("val", val);
        this.multipleSelection = val;
      }
    }
  };
</script>
<style lang="scss" scoped></style>
